<template>
  <div class="fixed inset-0 bg-gray-600 bg-opacity-50 overflow-y-auto h-full w-full z-50" @click="handleBackdropClick">
    <div class="relative top-20 mx-auto p-5 border w-11/12 md:w-3/4 lg:w-1/2 shadow-lg rounded-md bg-white">
      <!-- 标题 -->
      <div class="flex items-center justify-between mb-6">
        <h3 class="text-lg font-medium text-gray-900">
          提供目击线索
        </h3>
        <button
          @click="$emit('close')"
          class="text-gray-400 hover:text-gray-600"
        >
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <!-- 宠物信息展示 -->
      <div class="mb-6 p-4 bg-gray-50 rounded-lg">
        <div class="flex items-center space-x-4">
          <img
            v-if="post.pet?.photo_url"
            :src="getFullImageUrl(post.pet.photo_url)"
            :alt="post.pet.name"
            class="w-16 h-16 object-cover rounded-lg"
          />
          <div
            v-else
            class="w-16 h-16 bg-gray-200 rounded-lg flex items-center justify-center"
          >
            <svg class="w-8 h-8 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
          </div>
          <div>
            <h4 class="font-medium text-gray-900">{{ post.pet?.name }}</h4>
            <p class="text-sm text-gray-600">
              {{ post.pet?.species }} · {{ post.pet?.color }}
            </p>
            <p class="text-sm text-gray-500">
              走失地点：{{ post.last_seen_location }}
            </p>
          </div>
        </div>
      </div>

      <!-- 表单 -->
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <!-- 目擊時間 -->
        <div>
          <label for="sightingTime" class="block text-sm font-medium text-gray-700">
            目擊時間 <span class="text-red-500">*</span>
          </label>
          <input
            id="sightingTime"
            v-model="form.sighting_time"
            type="datetime-local"
            required
            class="mt-1 input-field"
          />
        </div>

        <!-- 目擊地點 -->
        <AddressPicker
          v-model="selectedAddress"
          label="目擊地點"
          placeholder="請輸入目擊地點"
          :required="true"
          help-text="請輸入詳細的目擊地點信息"
        />

        <!-- 目擊情況描述 -->
        <div>
          <label for="description" class="block text-sm font-medium text-gray-700">
            目擊情況描述（可選）
          </label>
          <textarea
            id="description"
            v-model="form.description"
            rows="3"
            class="mt-1 input-field"
            placeholder="請描述目擊時的情況，如寵物狀態、行為等"
          ></textarea>
        </div>

        <!-- 照片上傳 -->
        <ImageUpload
          v-model="form.photo"
          label="目擊照片（可選）"
          help-text="如果您拍攝了照片，請上傳以幫助確認"
        />

        <!-- 隱私說明 -->
        <div class="bg-blue-50 border border-blue-200 rounded-md p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <svg class="h-5 w-5 text-blue-400" viewBox="0 0 20 20" fill="currentColor">
                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
              </svg>
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-blue-800">
                隱私保護
              </h3>
              <div class="mt-2 text-sm text-blue-700">
                <p>
                  您的線索將匿名提交，只有失主能看到。我們不會收集您的個人信息。
                </p>
              </div>
            </div>
          </div>
        </div>

        <!-- 錯誤提示 -->
        <div v-if="error" class="rounded-md bg-red-50 p-4">
          <div class="flex">
            <div class="flex-shrink-0">
              <ExclamationTriangleIcon class="h-5 w-5 text-red-400" />
            </div>
            <div class="ml-3">
              <h3 class="text-sm font-medium text-red-800">
                {{ error }}
              </h3>
            </div>
          </div>
        </div>

        <!-- 操作按鈕 -->
        <div class="flex justify-end space-x-3">
          <button
            type="button"
            @click="$emit('close')"
            class="btn-secondary"
          >
            取消
          </button>
          <button
            type="submit"
            :disabled="loading || !canSubmit"
            class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <span v-if="loading" class="flex items-center">
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              提交中...
            </span>
            <span v-else>提交線索</span>
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ExclamationTriangleIcon } from '@heroicons/vue/24/outline'
import { sightingService } from '@/services/sightings'
import ImageUpload from '@/components/ImageUpload.vue'
import AddressPicker from '@/components/AddressPicker.vue'
import { getFullImageUrl } from '@/utils/helpers'
import type { Post, SightingFormData } from '@/types'

interface Props {
  post: Post
}

interface Emits {
  (e: 'close'): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态
const loading = ref(false)
const error = ref('')

// 表单数据
const form = ref<SightingFormData>({
  post_id: props.post.id,
  sighting_location: '',
  sighting_time: '',
  description: '',
  photo: null,
})

const selectedAddress = ref<string>('')

// 计算属性
const canSubmit = computed(() => {
  return form.value.sighting_time && selectedAddress.value.trim()
})

// 方法
const handleBackdropClick = (event: MouseEvent) => {
  if (event.target === event.currentTarget) {
    emit('close')
  }
}

const handleSubmit = async () => {
  if (!canSubmit.value) return

  try {
    loading.value = true
    error.value = ''

    // 设置地点信息
    form.value.sighting_location = selectedAddress.value

    const response = await sightingService.submit(form.value)

    if (response.success) {
      emit('success')
      emit('close')
    } else {
      error.value = response.message || '提交失败'
    }
  } catch (err: any) {
    console.error('提交线索失败:', err)
    error.value = err.message || '提交失败，请稍后重试'
  } finally {
    loading.value = false
  }
}
</script>
